﻿using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using WD.Core.Upload;
using WD.Framework.Contract;

namespace WD.Web
{
    public class UploadHandle
    {
        private const string UploadPath = "/Upload";
        private static readonly string[] ImageExt = new[] { "jpg", "jpeg", "gif", "png" };

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="config"></param>
        /// <param name="context"></param>
        /// <param name="localFileName">输出参数 返回原文件名</param>
        /// <returns>新文件名</returns>
        public string SaveFile(UploadConfig config, HttpContextBase context, out string localFileName)
        {
            context.Response.Charset = "UTF-8";

            byte[] file;
            localFileName = string.Empty;
            var err = string.Empty;
            var subFolder = string.Empty;
            var fileFolder = string.Empty;
            var filePath = string.Empty;

            var disposition = context.Request.ServerVariables["HTTP_CONTENT_DISPOSITION"];
            if (disposition != null)
            {
                // HTML5上传
                file = context.Request.BinaryRead(context.Request.TotalBytes);
                localFileName = Regex.Match(disposition, "filename=\"(.+?)\"").Groups[1].Value; // 读取原始文件名
            }
            else
            {
                var filecollection = context.Request.Files;
                var postedfile = filecollection.Get(config.FileInputName);
                if (postedfile == null)
                {
                    throw new BusinessException("读取上传文件信息失败");
                }
                // 读取原始文件名
                localFileName = Path.GetFileName(postedfile.FileName);
                if (localFileName == null)
                {
                    throw new BusinessException("读取上传文件名失败");
                }
                // 初始化byte长度.
                file = new Byte[postedfile.ContentLength];

                // 转换为byte类型
                var stream = postedfile.InputStream;
                stream.Read(file, 0, postedfile.ContentLength);
                stream.Close();
            }

            var ext = localFileName.Substring(localFileName.LastIndexOf('.') + 1).ToLower();
            if (file.Length == 0)
                err = "无数据提交";
            else if (file.Length > config.MaxFilesize)
                err = "文件大小超过" + config.MaxFilesize + "字节";
            else if (!config.AllowExt.Contains(ext))
                err = "上传文件扩展名必需为：" + string.Join(",", config.AllowExt);
            else
            {
                config.Path = config.Path.EndsWith("/") ? config.Path : (config.Path + "/");
                fileFolder = context.Server.MapPath(UploadPath + config.Path);
                //生成文件名
                var fileName = string.IsNullOrWhiteSpace(config.FileName)
                                   ? string.Format("{0}{1}.{2}", DateTime.Now.ToString("yyyyMMddhhmmss"),
                                                   new Random(DateTime.Now.Millisecond).Next(10000), ext)
                                   : config.FileName + "." + ext;

                filePath = Path.Combine(fileFolder, fileName);

                if (!Directory.Exists(fileFolder))
                    Directory.CreateDirectory(fileFolder);

                var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                fs.Write(file, 0, file.Length);
                fs.Flush();
                fs.Close();

                //是图片，即使生成对应尺寸
                if (ImageExt.Contains(ext))
                {
                    //TODO 生成缩略图  以后添加             
                    //var thumbnailFileFolder = string.Format("{0}\\thumb", fileFolder);
                    //var thumbnailFilePath = string.Format("{0}\\{1}_{2}_{3}{4}", thumbnailFileFolder, fileName, size.Width, size.Height, ext);
                    //ThumbnailHelper.MakeThumbnail(filePath, thumbnailFilePath, size);

                }
                return fileName;
            }
            if (!string.IsNullOrWhiteSpace(err))
            {
                throw new BusinessException(err);
            }
            return "";
        }
    }

    /// <summary>
    /// 上传文件配置
    /// </summary>
    public class UploadConfig
    {
        /// <summary>
        /// 默认配置 大小限制10M，控件Name=filedata，后缀名{ "jpg", "jpeg", "gif", "png" }
        /// </summary>
        public UploadConfig()
        {
            MaxFilesize = 10971520;     //10M 
            FileInputName = "filedata";
            AllowExt = new[] { "jpg", "jpeg", "gif", "png" };
        }

        /// <summary>
        /// 保存路径
        /// </summary>
        public string Path { get; set; }

        /// <summary>
        /// 上传控件Name
        /// </summary>
        public string FileInputName { get; set; }

        /// <summary>
        /// 单个文件限制大小
        /// </summary>
        public int MaxFilesize { get; set; }

        /// <summary>
        /// 允许的后缀名
        /// </summary>
        public string[] AllowExt { get; set; }

        /// <summary>
        /// 保存后的文件名（不带后缀名。如果为空则随机生成）
        /// </summary>
        public string FileName { get; set; }
    }
}
